<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle" @click="gotoUrl(obj)"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
// import china from "@/assets/json/china.json"
// import china_city from "@/assets/json/china_cities.json"
// import world from "@/assets/json/world.json"
// import { cardDataLoad, boardLoad } from '@/api/share'

export default {
    Name: "EchartMap",
    components: {
        echarts
    },
    props: {
        obj: Object,
        discount: Number,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
    },
    data() {
        return {
            showContent: true,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            timer: null,
            filterForm: {
                pageInfo: {
                    pageSize: 9999,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);
            this.getLineData();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // if (this.isReload) {
        //     this.timer = setInterval(() => {
        //         this.getLineData();
        //     }, 62000);
        // }

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            self.chart.resize();
        }, true);
    },
    beforeDestroy() {
        clearInterval(this.timer)
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null;
    },
    methods: {
        gotoUrl() {
            if (this.isEdit == false && this.obj.contactType > 0) {
                if (this.obj.contactType == 1 && this.obj.boardId) {
                    this.$router.replace({ path: `/share/${this.obj.boardId}` })
                }
                if (this.obj.contactType == 2 && this.obj.url) {
                    this.$router.replace(this.obj.url);
                }
            }
        },
        computedDiscount(number) {
            if (number > 0 && this.discount > 0) {
                var newNumber = Math.floor(number * this.discount);
                if (newNumber < 10) {
                    return 0;
                }
                return newNumber;
            }
            return number;
        },
        getLineData() {
            if (this.obj.tableData && this.obj.tableData.tableId && this.obj.tableData.nameid && this.obj.tableData.valueid) {
                this.filterForm.tableId = this.obj.tableData.tableId;

                var idlist = [this.obj.tableData.nameid, this.obj.tableData.valueid];

                if (this.obj.tableData.itemid) {
                    idlist = idlist.concat(this.obj.tableData.itemid)
                }
                var self = this;

                this.filterForm.structureIds = idlist;

                if (this.obj.tableData.type != 1) {
                    cardDataLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var data = [];
                            var datalist = res.data.data.dataResult.dataList;
                            var columnslist = res.data.data.dataResult.columns;
                            if (datalist && datalist.length) {
                                for (var i = 0; i < datalist.length; i++) {
                                    var datainfo = {};
                                    var tooltip = [];
                                    for (var j = 0; j < columnslist.length; j++) {
                                        if (j == 0) {
                                            datainfo.name = datalist[i][j]
                                        }
                                        if (j == 1) {
                                            datainfo.value = datalist[i][j]
                                        }
                                        if (j > 0) {
                                            tooltip.push({ name: columnslist[j].name, value: datalist[i][j] })
                                        }
                                        // data.push({ name: datalist[i][0], value: datalist[i][1] });
                                    }
                                    datainfo.tooltip = tooltip;
                                    data.push(datainfo);
                                }
                                console.log(data)
                            }
                            this.setOptions(data);
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                } else {
                    boardLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var data = [];
                            var datalist = res.data.data.dataResult.dataList;
                            if (datalist && datalist.length) {
                                for (var i = 0; i < datalist.length; i++) {
                                    data.push({ name: datalist[i][0], value: datalist[i][1] });
                                }
                            }
                            this.setOptions(data);
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                }
            } else {
                this.setOptions(null);
            }
        },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";
            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "#04142b";
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            this.titleStyle = {
                justifyContent: style.justifyContent,
                // alignItems: style.alignItems,
            }

            this.canvasStyle = {
                width: style.width,
                height: style.height,
            }
            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: style.height,
                });
            }
        },
        setOptions(data) {
            this.chart.showLoading();
            // axios.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json').then(res => {
            this.chart.hideLoading();
            if (this.obj.tableData.maptype == 0) {
                echarts.registerMap('china', world);
            } else if (this.obj.tableData.maptype == 1) {
                echarts.registerMap('china', china);
            } else if (this.obj.tableData.maptype == 2) {
                echarts.registerMap('china', china_city);
            }

            // #region legend样 式
            var textColor = "#333333";
            if (this.obj.tableData.textColor) {
                textColor = this.obj.tableData.textColor;
            }
            var textFontsize = '14px';
            if (this.obj.tableData.textfontSize) {
                textFontsize = this.obj.tableData.textfontSize + "px";
            }
            var textFontWeight = "";
            if (this.obj.tableData.textFontWeight) {
                textFontWeight = this.obj.tableData.textFontWeight;
            }
            var textFontStyle = "";
            if (this.obj.tableData.textFontStyle) {
                textFontStyle = this.obj.tableData.textFontStyle;
            }
            // #endregion

            // console.log(data)
            var nameMap = data.map(res => { return res.name; })
            //  text
            //         var convertLineData = function (data) {
            //             var res = [];
            //             for (var i = 0; i < data.length; i++) {
            //                 var dataItem = data[i];
            //                 var coordS = dataItem.lineS; //线起点
            //                 var coordM = dataItem.lineM; //线中间点
            //                 var coordE = dataItem.lineE; //线尾点
            //                 if (coordS && coordM && coordE) {
            //                     res.push({
            //                         coords: [coordS, coordM, coordE]
            //                     });
            //                 }
            //             }
            //             return res;
            //         };
            //         var convertValData = function (data) {
            //             var res = [];
            //             for (var i = 0; i < data.length; i++) {
            //                 var dataItem = data[i];
            //                 res.push({
            //                     name: dataItem.areaName,
            //                     value: dataItem.lineE.concat(dataItem.value)
            //                 });
            //             }
            //             return res;
            //         };
            //         var json = {
            //             data: [{
            //                 areaName: '北京',
            //                 value: 94,
            //                 lineS: [116.4551, 40.2539],
            //                 lineM: [125.541, 40.4242],
            //                 lineE: [135.4648, 43.2891]
            //             }, {
            //                 areaName: '上海',
            //                 value: 90,
            //                 lineS: [121.4648, 31.2891],
            //                 lineM: [125.4648, 31.2891],
            //                 lineE: [127.4648, 36.2891]
            //             }]
            //         };
            //         var data = json.data;
            //         var series = [];
            //         series.push(
            //             {
            //                 name: '',
            //                 type: 'lines',
            //                 zlevel: 2,
            //                 symbol: 'none',
            //                 silent: true, //不响应鼠标点击或事件
            //                 effect: {
            //                     show: false //关闭特效
            //                 },
            //                 tooltip: {
            //                     show: false
            //                 },
            //                 polyline: true, //支持多点连线
            //                 lineStyle: {
            //                     normal: {
            //                         color: 'white',
            //                         width: 1.5,
            //                         opacity: 0.9,
            //                         curveness: 0
            //                     }
            //                 },
            //                 data: convertLineData(data)
            //             },
            //             {
            //                 name: '',
            //                 type: 'scatter',
            //                 coordinateSystem: 'geo',
            //                 zlevel: 2,
            //                 hoverAnimation: false, //hover时不高亮点
            //                 cursor: 'default', //鼠标设置为箭头
            //                 itemStyle: {
            //                     normal: {
            //                         color: 'orange'
            //                     }
            //                 },
            //                 tooltip: {
            //                     show: false
            //                 },
            //                 label: {
            //                     normal: {
            //                         show: true,
            //                         position: 'right',
            //                         fontSize: 25,
            //                         fontWeight: 'bold',
            //                         color: '#f5a623',
            //                         formatter: function (param) {
            //                             return param.value[2];
            //                         }
            //                     }
            //                 },
            //                 data: convertValData(data)/*[{
            //                     name: '94', value: [135.4648, 43.2891, 95],

            //                 }]*/
            //             }
            //         );

            // this.chart.setOption(series);
            // return false;
            // test
            // console.log(data)

            let LableData = [
                {
                    name: "北京",
                    coords: [
                        [116.4551, 40.2539],
                        [125.8029, 40.5567]
                    ],
                },
                {
                    name: "上海",
                    coords: [
                        [121.4648, 31.2891],
                        [125.9133, 32.3368]
                    ],
                },
            ];

            var shouLineData = [];


            var series = [
                {
                    type: 'map',
                    map: 'china',
                    // roam: 'scale',
                    label: {
                        show: this.obj.tableData.isShowName,
                        formatter(v) {
                            if (nameMap.indexOf(v.name) >= 0) {
                                return v.name;
                            }
                            return "";
                        },
                        color: textColor,
                        fontSize: textFontsize,
                        fontWeight: textFontWeight,
                        fontStyle: textFontStyle,
                    },
                    top: 0,
                    left: 0,
                    right: 0,
                    data: data,
                    itemStyle: {
                        areaColor: this.obj.tableData.backgroundColor,
                        borderColor: this.obj.tableData.borderColor
                    },
                    emphasis: {
                        itemStyle: {
                            areaColor: this.obj.tableData.hoverColor
                        }
                    },
                    select: {
                        itemStyle: {
                            areaColor: this.obj.tableData.hoverColor
                        },
                    }
                },
            ];
            // console.log(shouLineData)
            if (this.obj.tableData.isShowLine) {
                for (var i = 0; i < LableData.length; i++) {
                    data.forEach(res => {
                        if (res.name == LableData[i].name) {
                            LableData[i].value = res.tooltip;
                            shouLineData.push(LableData[i]);
                        }
                    });
                }

                series.push({
                    type: 'lines',
                    zlevel: 3,
                    symbol: 'circle',
                    symbolSize: [5, 5],
                    color: '#ff8003',
                    opacity: 1,
                    label: {
                        show: true,
                        padding: [10, 20],
                        color: '#fff',
                        backgroundColor: "#1a3961",
                        borderColor: '#aee9fb',
                        borderWidth: 1,
                        borderRadius: 6,
                        formatter(item) {
                            var str = [item.name];

                            for (var i = 0; i < item.value.length; i++) {
                                var tool = item.value[i];
                                str.push(`${tool.name}：${tool.value}`);
                            }
                            // return `${item.name}：${item.value}`;
                            return str.join("\n");
                        },
                        textStyle: {
                            align: 'left',
                            lineHeight: 20,
                        },
                    },
                    lineStyle: {
                        type: 'solid',
                        width: 0.5,
                        opacity: 1,
                        color: "#1a3961"
                    },
                    data: shouLineData,
                });
            }
            this.chart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: function (item) {
                        if (Number.isNaN(item.value)) {
                            return "";
                        }
                        //  console.log(item)

                        var str = "";

                        for (var i = 0; i < item.data.tooltip.length; i++) {
                            var tool = item.data.tooltip[i];
                            str += `${tool.name}：${tool.value}<br>`;
                        }
                        // return `${item.name}：${item.value}`;
                        return str;
                    }
                },
                visualMap: {
                    show: false,
                    min: this.obj.tableData.min,
                    max: this.obj.tableData.max,
                    text: ['High', 'Low'],
                    // realtime: false,
                    // calculable: true,
                    inRange: {
                        color: [this.obj.tableData.color1, this.obj.tableData.color2]
                    },
                    seriesIndex: 0,
                },
                geo: {
                    label: {
                        show: false
                    },
                    type: 'map',
                    map: 'china',
                    // roam: false,
                    // aspectScale: 1,
                    // zoom: 1,
                    top: 0,
                    // bottom: 0,
                    left: 0,
                    right: 0,
                    label: {
                        show: this.obj.tableData.isShowName,
                        formatter(v) {
                            if (nameMap.indexOf(v.name) >= 0) {
                                return v.name;
                            }
                            return "";
                        },
                        color: textColor,
                        fontSize: textFontsize,
                        fontWeight: textFontWeight,
                        fontStyle: textFontStyle,
                    },
                },
                series: series
            })
            // });
        },
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    // 重绘
                    this.chart.dispose()
                    var constat = this.$refs.constat;
                    this.chart = echarts.init(constat);

                    this.getLineData();
                }
            },
            deep: true,
        }
    },
}
</script>